package xjay.ai.emotionalsupport.rag;

import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service

public class DivinationRag extends RagService {


    public DivinationRag(ResourcePatternResolver resolver, @Qualifier("pgVectorStore") VectorStore vectorStore) {
        super.setMarkdownResourcePath("classpath:document/divination/*.md");
        super.setPdfResourcePath("classpath:document/divination/*.pdf");
        super.setResolver(resolver);
        super.setVectorStore(vectorStore);
    }


    public VectorStore rag() {
        // 检查向量数据库是否为空，避免重复添加文档
        if (isVectorStoreEmpty()) {
            getVectorStore().add(documents);
        }
        return getVectorStore();
    }

    /**
     * 检查向量数据库是否为空或需要更新
     * @return true if empty or needs update, false otherwise
     */
    private boolean isVectorStoreEmpty() {
        try {
            // 尝试搜索任意内容，如果没有结果说明数据库为空
            List<Document> searchResults = getVectorStore().similaritySearch("test");
            if (searchResults.isEmpty()) {
                return true;
            }

            // 检查是否存在特定的版本标记文档
            var versionResults = getVectorStore().similaritySearch("DIVINATION_DOCS_VERSION");
            return versionResults.isEmpty();
        } catch (Exception e) {
            // 如果出现异常（如表不存在），认为数据库为空
            return true;
        }
    }

    /**
     * 安全地初始化向量数据库
     * 包含版本控制和重复检查
     */
    public VectorStore safeInitializeRag() throws IOException {
        if (isVectorStoreEmpty()) {
            // 清空现有文档列表
            documents.clear();

            // 重新加载文档
            loadMarkdown();
            loadPDF();

            // 添加版本标记文档
            Document versionDoc = new Document("DIVINATION_DOCS_VERSION: " + System.currentTimeMillis());
            versionDoc.getMetadata().put("type", "version_marker");
            versionDoc.getMetadata().put("timestamp", String.valueOf(System.currentTimeMillis()));
            documents.add(versionDoc);

            // 添加到向量数据库
            getVectorStore().add(documents);
        }
        return getVectorStore();
    }
}
